import { Request, toast, alert, fileUrl } from '../../utils/util.js'
let request = new Request()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: 0,
    user: {},
    praiseNumber : 0,
    followed : false,
    isAgent : false,
    picture : []
  },

  toggleFollow () {
    let followed = this.data.followed
    let url = followed ? 'visit/unfollow' : 'visit/follow'
    request.post(url, res => {
      if(res.success) {
        this.setData({ followed: !followed})
      }else{
        toast(res.msg)
      }
    }, {userId : this.data.userId})
  },

  navTo () {
    let user = this.data.user
    wx.navigateTo({
      url: `/pages/applyAgent/index?storeId=${user.user_id}&storeName=${user.nickname}`
    })
  },

  onLoad: function (options) {
    let userId = options.userId
    if(userId <= 0){
      alert('访问不了啦~')
      return
    }
    request.get('visit/homepage', res => {
      if(res.success) {
        let data = res.data
        let user = res.data.user
        if (!(user instanceof Object)) {
          user = JSON.parse(user)
        }
        if(user.background) {
          user.background = fileUrl(user.background)
        }
        if (typeof user.label === 'string') {
          user.label = JSON.parse(user.label)
        }

        this.setData({ user: user, picture: data.picture, followed: data.followed, isAgent: data.is_agent, praiseNumber: data.praise_number})
        wx.setNavigationBarTitle({
          title: user.nickname,
        })
      }else{
        alert(res.msg)
      }
    }, {userId : userId})
    this.setData({ userId: userId})
  }
})